#include "../logger/log.h"
#include <chrono>
using namespace ns_logger;

void bench(const std::string &logger_name, size_t thr_count, size_t msg_count, size_t msg_len)
{
    // 1.获取日志器
    LoggerPtr lg = getLogger(logger_name);
    if (!lg.get())
    {
        std::cout << "不存在日志器:" << logger_name << std::endl;
        return;
    }
    // 2.创建消息
    std::string msg(msg_len - 1, 'A');
    std::cout << "线程数量:" << thr_count << "个,消息数量:" << msg_count << "条,消息总大小:" << (msg_count * msg_len) / (1024*1024) << "(MB)" << std::endl;
    // 3.创建线程
    std::vector<std::thread> threads;
    std::vector<double> cost(thr_count);
    // 计算每个线程处理多少条消息
    size_t msg_per_thr = msg_count / thr_count;
    for (int i = 0; i < thr_count; i++)
    {
        threads.emplace_back([&, i]()
                             {
            //开始计时
            auto start=std::chrono::high_resolution_clock::now();
            //开始循环写日志
            for(int j=0;j<msg_per_thr;j++){
                lg->Fatal("%s",msg.c_str());
            }
            //结束计时
            auto end=std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> diff=end-start;
            cost[i]=diff.count();
            std::cout<<"线程"<<i<<"耗时:"<<diff.count()<<"s,处理"<<msg_per_thr<<"条消息\n"; });
    }
    for (auto &thr : threads)
    {
        thr.join();
    }
    double maxcost = cost[0];
    for (int i = 1; i < thr_count; i++)
    {
        maxcost = std::max(maxcost, cost[i]);
    }
    size_t msg_per_sec = msg_count / maxcost;
    size_t size_per_sec = (msg_count * msg_len) / (maxcost * 1024*1024);
    std::cout << "总耗时:" << maxcost << std::endl;
    std::cout << "每秒输出:" << msg_per_sec << "条消息" << std::endl;
    std::cout << "每秒输出:" << size_per_sec << "(MB)" << std::endl;
}

void async_bench()
{
    std::cout << "开始性能测试:当前是异步写日志\n";
    std::shared_ptr<LoggerBuilde> builder(new GlobalLoggerBuilder());
    builder->BuildFormat(":%m%n");
    builder->BuildName("async_logger");
    builder->BuildType(LogType::ASYNC);
    builder->BuildSink<FileSink>("./log/sync.text");
    builder->EnableUnSafe();
    builder->build();
    bench("async_logger", 5, 10000000, 100);
}

void sync_bench()
{
    std::cout << "开始性能测试:当前是同步写日志\n";
    std::shared_ptr<LoggerBuilde> builder(new GlobalLoggerBuilder());
    builder->BuildFormat("%m%n");
    builder->BuildName("sync_logger");
    builder->BuildType(LogType::SYNC);
    builder->BuildSink<FileSink>("./log/sync.text");
    builder->build();
    bench("sync_logger", 5, 10000000, 100);
}

int main()
{
    async_bench();
    //sync_bench();
}
